package com.steve.xfood.controller;

import com.steve.xfood.dataobject.ProductCategory;
import com.steve.xfood.dataobject.ProductInfo;
import com.steve.xfood.enums.ResultEnum;
import com.steve.xfood.exception.XFoodException;
import com.steve.xfood.form.ProductForm;
import com.steve.xfood.service.ProductCategoryService;
import com.steve.xfood.service.ProductInfoService;
import com.steve.xfood.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 卖家端商品
 * @author steve
 * @date 2020/5/22 13:47
 */
@Controller
@RequestMapping("/seller/product")
@Slf4j
public class SellerProductController {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private ProductCategoryService productCategoryService;

    /**
     * 显示商品列表
     * @param page
     * @param size
     * @param map
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "size",defaultValue = "5") int size,
                             Map<String, Object> map) {
        //PageRequest pageRequest = new PageRequest(page, size); springboot 1.5
        PageRequest pageRequest = PageRequest.of(page-1, size);
        Page<ProductInfo> productInfoPage = productInfoService.findAll(pageRequest);
        log.info("【查询商品详情】 商品列表={}", productInfoPage.getContent());
        map.put("productInfoPage", productInfoPage);
        map.put("currentPage", page);
        map.put("size", size);
        return new ModelAndView("product/list", map);
    }

    /**
     * 商品修改上架状态
     * @param productId
     * @param map
     * @return
     */
    @GetMapping("on-sale")
    public ModelAndView onSale(@RequestParam("productId") String productId,
                               Map<String, Object> map) {
        try {
            productInfoService.onSale(productId);
        }catch (XFoodException e) {
            //设置在成功页面的提示消息和跳转
            map.put("msg", e.getMessage());
            map.put("url","/sell/seller/product/list");
            return new ModelAndView("common/error", map);
        }
        map.put("msg", ResultEnum.SUCCESS.getMessage());
        map.put("url","/sell/seller/product/list");
        return new ModelAndView("common/success", map);
    }

    /**
     * 商品修改下架状态
     * @param productId
     * @param map
     * @return
     */
    @GetMapping("off-sale")
    public ModelAndView offSale(@RequestParam("productId") String productId,
                               Map<String, Object> map) {
        try {
            productInfoService.offSale(productId);
        }catch (XFoodException e) {
            //设置在成功页面的提示消息和跳转
            map.put("msg", e.getMessage());
            map.put("url","/sell/seller/product/list");
            return new ModelAndView("common/error", map);
        }
        map.put("msg", ResultEnum.SUCCESS.getMessage());
        map.put("url","/sell/seller/product/list");
        return new ModelAndView("common/success",map);
    }

    /**
     * 修改商品数据回显
     * @param productId
     * @param map
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "productId", required = false) String productId,
                              Map<String, Object> map) {
        if (!StringUtils.isEmpty(productId)) {
            //商品id不为空
            ProductInfo productInfo = productInfoService.findById(productId);
            map.put("productInfo", productInfo);
        }
        //查询商品所有类目
        List<ProductCategory> categoryList = productCategoryService.findAll();
        map.put("categoryList", categoryList);

        return new ModelAndView("product/index",map);
    }

    /**
     * 修改/新增商品
     * @param productForm 前端参数封装实体类
     * @param bindingResult 参数校验结果
     * @param map
     * @return
     */
    @PostMapping("/save")
    //@CachePut(cacheNames = "product", key = "123") //使用CachePut的话，存储的对象和返回的对象必须一致，不然会存储失败
    @CacheEvict(cacheNames = "product", key = "123") //清除缓存，访问方法后，会把缓存清除。查询的时候重新生成缓存
    public ModelAndView save(@Valid ProductForm productForm, BindingResult bindingResult,Map<String, Object> map) {
        if (bindingResult.hasErrors()) {
            //如果参数校验失败，则弹出提示信息，并跳转回修改商品页面
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/sell/seller/product/index");
            return new ModelAndView("/common/error", map);
        }
        ProductInfo productInfo = new ProductInfo();
        try {
            if (StringUtils.isEmpty(productForm.getProductId())) {
                //没有传递productId, 说明是新增商品
                //设置商品id
                productForm.setProductId(KeyUtil.genUniqueKey());
                BeanUtils.copyProperties(productForm, productInfo);
                //新增商品
                productInfoService.save(productInfo);
            }
            productInfo = productInfoService.findById(productForm.getProductId());
            //把前端表单提交的参数，替换到商品实体类中
            BeanUtils.copyProperties(productForm, productInfo);
            //修改商品
            productInfoService.save(productInfo);
        } catch (XFoodException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/product/index");
            return new ModelAndView("common/error", map);
        }
        map.put("msg", ResultEnum.SUCCESS.getMessage());
        map.put("url", "/sell/seller/product/list");
        return new ModelAndView("common/success",map);
    }

}
